package com.kalvan.core.utils;

import com.kalvan.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenliang
 */
@Slf4j
public class BeanUtils {


    /**
     * 将数据并copy到新bean中
     *
     * @param source source
     * @param target target
     * @param <T>    T
     * @return T
     */
    public static <T> T newAndCopy(Object source, Class<T> target) {
        try {
            T t = target.newInstance();
            org.springframework.beans.BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            log.error("copy error", e);
            throw new BizException("copy error");
        }

    }

    /**
     * 将list数据copy到另外一个list
     *
     * @param sourceList  sourceList
     * @param targetClass targetClass
     * @return List
     */
    public static List copyList(List sourceList, Class targetClass) {
        List newArrayList = new ArrayList();
        try {
            for (Object source : sourceList) {
                Object t = targetClass.newInstance();
                org.springframework.beans.BeanUtils.copyProperties(source, t);
                newArrayList.add(t);
            }
        } catch (Exception e) {
            log.error("copy error", e);
            throw new BizException("copy error");
        }
        return newArrayList;
    }
}
